package com.aifeng.fragment

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.SimpleItemAnimator
import com.aifeng.base.*
import com.aifeng.common_ui.base.*
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyGridLayoutManager
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.sale.ConfirmActivity
import com.aifeng.hassan_food.sale.DetailActivity
import com.aifeng.model.CommonData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.GoodsViewModel
import com.chauthai.swipereveallayout.SwipeRevealLayout
import com.chauthai.swipereveallayout.setOnSwipeListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.fragment_main_three.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainThreeFragment : BaseFragment() {

    private lateinit var mGridAdapter: SlimAdapter
    private val mList = ArrayList<CommonData>()
    private val innerList = ArrayList<CommonData>()
    private val mLayouts = HashMap<String, SwipeRevealLayout>()

    //调用这个方法切换时不会释放掉Fragment
    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        this.view?.visibility = if (menuVisible) View.VISIBLE else View.GONE
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_main_three, container, false)

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initTitle()

        getViewModel().resultEvent
            .observe(
                getLifecycleOwner(),
                Observer {
                    if (it.isEmpty()) {
                        three_check.isChecked = false
                        three_total.text = "¥ 0.00"
                        three_resale.text = "¥ 0.00"
                        three_done.text = "去结算(0)"
                    } else {
                        val selectCount = it[2].toNotInt()
                        three_check.setOnCheckedChangeListener(null)
                        three_check.isChecked = selectCount == mList.size
                        three_check.setOnCheckedChangeListener(this)
                        three_total.text = "¥ ${it[0]}"
                        three_resale.text = "¥ ${it[1]}"
                        three_done.text = "去结算($selectCount)"
                    }
                }
            )

        three_swipe.isRefreshing = true
        getData()
        getRecommendData()
    }

    override fun getViewModel() = getViewModel<GoodsViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle() {
        @Suppress("DEPRECATION")
        val drawable = resources.getDrawable(R.drawable.ic_adress_selector)
        drawable.setBounds(0, 0, dp2px(14f), dp2px(14f))
        three_check.setCompoundDrawables(drawable, null, null, null)

        three_swipe.refresh { getData() }

        three_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去除闪烁

            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_three_list) { inner, jector ->
                    val index = mList.indexOf(inner)
                    val isLast = index == mList.size - 1

                    jector.text(R.id.item_three_name, inner.goodname)
                        .text(R.id.item_three_price, inner.price.formatDecimal())
                        .text(R.id.item_three_num, inner.num)
                        .image(
                            R.id.item_three_check,
                            if (inner.isChecked) R.mipmap.icon_check_b else R.mipmap.icon_check
                        )
                        .with<SwipeRevealLayout>(R.id.item_three_layout) { view ->
                            view.close(true)
                            if (!mLayouts.containsKey(inner.id)) mLayouts[inner.id] = view

                            view.setOnSwipeListener {
                                onOpened {
                                    if (mList.any { it.state == 2 }) {
                                        val item = mList.first { it.state == 2 }
                                        mLayouts[item.id]?.close(true)
                                    }
                                    inner.state = 2
                                }
                                onClosed { inner.state = 0 }
                            }
                        }
                        .with<TextView>(R.id.item_three_origin) {
                            it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                            it.text = "¥ ${inner.orgprice.formatDecimalWhenHave()}"
                        }
                        .with<ImageView>(R.id.item_three_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadRoundedImage(url = imgs[0].scaleImage())
                        }
                        .visibility(
                            R.id.item_three_divider,
                            if (isLast) View.GONE else View.VISIBLE
                        )
                        .clicked(R.id.item_three_plus) {
                            if (inner.num.toNotInt() == 1) {
                                showToast("最少购买一件商品！")
                                return@clicked
                            }

                            changeNum(inner.goodsid, index, -1)
                        }
                        .clicked(R.id.item_three_add) {
                            changeNum(inner.goodsid, index, 1)
                        }
                        .clicked(R.id.item_three_check) {
                            inner.isChecked = !inner.isChecked
                            mAdapter.notifyItemChanged(index)
                            getViewModel().calculateTotal(mList)
                        }
                        .clicked(R.id.item_three_delete) {
                            deleteItem(inner.id, index, inner.isChecked)
                        }
                        .longClicked(R.id.item_three) {
                            deleteItem(inner.id, index, inner.isChecked)
                            true
                        }
                }
                .attachTo(this)
        }

        three_list1.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyGridLayoutManager(getIContext(), 2)
            mGridAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_three_grid) { inner, jector ->
                    jector.text(R.id.item_three_name, inner.goodname)
                        .text(
                            R.id.item_three_price,
                            setHtmlSmall("¥ ${inner.price.formatDecimal()}", "¥")
                        )
                        .with<TextView>(R.id.item_three_orgin) {
                            it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                            it.text = "¥ ${inner.orgprice.formatDecimalWhenHave()}"
                        }
                        .with<ImageView>(R.id.item_three_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadImage(url = imgs[0].scaleImage(320, 320))
                        }
                        .visibility(
                            R.id.item_three_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_three_add) { view ->
                            getViewModel().addToCar(
                                inner.id,
                                getString("userId"),
                                1
                            )
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeByNoError(
                                    event = getViewModel(),
                                    onSuccess = {
                                        val position = IntArray(2)
                                        view.getLocationInWindow(position)
                                        LiveEventBus.get("carList").post("refresh")
                                        LiveEventBus.get("updateNum")
                                            .post("${position[0]},${position[1]},$it")
                                    }
                                )
                        }
                        .clicked(R.id.item_three) {
                            startActivityEx<DetailActivity>("id" to inner.id)
                        }
                }
                .attachTo(this)
        }

        three_clear.oneClick { clearCar() }
        three_check.setOnCheckedChangeListener(this)
        three_check.oneTouch(
            handle = {
                mList.isEmpty() && it.action == MotionEvent.ACTION_UP
            }
        )
        three_done.oneClick {
            getViewModel()
                .getCheckJson(mList) { json ->
                    startActivityEx<ConfirmActivity>(
                        "json" to json,
                        "data" to mList.filter { it.isChecked }
                    )
                }
        }

        observe("carList") {
            three_swipe.isRefreshing = true
            getData()
        }
    }

    private fun changeNum(id: String, index: Int, num: Int) {
        getViewModel().addToCar(
            id,
            getString("userId"),
            num
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                onSuccess = {
                    mList[index].num = (mList[index].num.toNotInt() + num).toString()

                    mAdapter.notifyItemChanged(index)
                    mAdapter.notifyItemChanged(index)
                    if (mList[index].isChecked)
                        getViewModel().calculateTotal(mList)
                }
            )
    }

    private fun deleteItem(id: String, index: Int, isChecked: Boolean) {
        getIContext().showHintDialog(
            title = "删除商品",
            hint = "确定要删除该商品吗？",
            sure = "删除"
        ) {
            getViewModel().deleteCar(id, getString("userId"))
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        mList.removeAt(index)
                        mAdapter.notifyDataSetChanged()
                        three_empty.apply { if (mList.isEmpty()) visible() else gone() }

                        LiveEventBus.get("updateNum").post(mList.size.toString())
                        if (isChecked) {
                            getViewModel().calculateTotal(mList)
                        }
                    }
                )
        }
    }

    private fun clearCar() {
        if (mList.isNotEmpty()) {
            getIContext().showHintDialog(
                title = "清空购物车",
                hint = "确定要清空购物车吗？",
                sure = "清空"
            ) {
                getViewModel().clearCar(getString("userId"))
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            mList.clear()
                            mAdapter.notifyDataSetChanged()
                            three_empty.visible()

                            LiveEventBus.get("updateNum").post("0")
                            getViewModel().calculateTotal(mList)
                        }
                    )
            }
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getCarList(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { items ->
                    mList.clear()
                    mList.addItems(items)
                    mList.forEach { it.isChecked = true }
                    mLayouts.clear()
                    mAdapter.updateData(mList)
                },
                onFinally = {
                    three_empty.apply { if (mList.isEmpty()) visible() else gone() }
                    getRecommendData()
                    getViewModel().calculateTotal(mList)
                }
            )
    }

    private fun getRecommendData() {
        getViewModel().getRecommendList(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    innerList.clear()
                    innerList.addItems(it)
                    mGridAdapter.updateData(innerList)
                },
                onFinally = {
                    three_swipe.isRefreshing = false
                }
            )
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { it.isChecked = isChecked }
        mAdapter.notifyDataSetChanged()
        getViewModel().calculateTotal(mList)
    }

}
